#define _CRT_SECURE_NO_WARNINGS 1

#include"sequence.h"

ST* SeqTableCreate()
{
	ST* obj = (ST*)malloc(sizeof(ST));
	if (obj == NULL)
	{
		perror("malloc error");
		exit(-1);
	}

	return obj;
}

void SeqTableInit(ST* obj, int capacity)
{
	assert(obj);

	Datetype* New = (Datetype*)malloc(sizeof(Datetype) * capacity);
	if (New == NULL)
	{
		perror("malloc error");
		exit(-1);
	}
	obj->head = New;
	obj->capacity = capacity;
	obj->top = 0;
}

void CheckCapacity(ST* obj)
{
	assert(obj);
	if (obj->capacity == obj->top)
	{
		obj->capacity = 2 * obj->capacity;
		Datetype* New = (Datetype*)realloc(obj->head, sizeof(Datetype) * obj->capacity);
		if (New == NULL)
		{
			perror("malloc error");
			exit(-1);
		}
		obj->head = New;
	}
}

void SeqTablePushFront(ST* obj, Datetype x)
{
	assert(obj);
	CheckCapacity(obj);

	int cur = obj->top;
	while (cur)
	{
		obj->head[cur] = obj->head[cur - 1];
		cur--;
	}
	obj->head[0] = x;
	obj->top++;
}

void SeqTablePushBack(ST* obj, Datetype x)
{
	assert(obj);
	CheckCapacity(obj);

	obj->head[obj->top] = x;
	obj->top++;
}

void SeqTablePopFront(ST* obj)
{
	assert(obj);

	int cur = 0;
	while (cur < obj->top - 1)
	{
		obj->head[cur] = obj->head[cur + 1];
		cur++;
	}
	obj->top--;
}

void SeqTablePopBack(ST* obj)
{
	assert(obj);

	obj->top--;
}

void SeqTableInsert(ST* obj, int pos, Datetype x)
{
	assert(obj);
	CheckCapacity(obj);

	int cur = obj->top;
	while (cur > pos)
	{
		obj->head[cur] = obj->head[cur - 1];
		cur--;
	}

	obj->head[pos] = x;
	obj->top++;
}

void SeqTableErase(ST* obj, int pos)
{
	assert(obj);

	int cur = pos;
	while (cur < obj->top - 1)
	{
		obj->head[cur] = obj->head[cur + 1];
		cur++;
	}
	obj->top--;
}

int SeqTableFind(ST* obj, Datetype x)
{
	assert(obj);

	int cur = 0;
	while (cur < obj->top)
	{
		if (obj->head[cur] == x)
		{
			return cur;
		}
	}
	return -1;
}

void SeqTableDestroy(ST* obj)
{
	assert(obj);

	free(obj->head);
	obj->head = NULL;
	free(obj);
}

void SeqTablePrint(ST* obj)
{
	assert(obj);

	int cur = 0;
	while (cur < obj->top)
	{
		printf("%d ", obj->head[cur]);
		cur++;
	}
	printf("\n");
}